package cn.zebra.dev.admin.module.admin.controller;

import cn.zebra.dev.admin.module.admin.dto.AdminInfoDTO;
import cn.zebra.dev.admin.module.admin.vo.LoginVO;
import cn.zebra.dev.admin.module.login.LoginService;
import cn.zebra.dev.admin.module.login.SecurityAdminService;
import cn.zebra.dev.base.module.admin.entity.BaseAdmin;
import cn.zebra.dev.common.constant.SysConstant;
import cn.zebra.dev.common.restful.Result;
import cn.zebra.dev.utils.module.kaptcha.ImageUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author runnable@sina.cn
 */
@RestController
@Api(tags = "登录服务")
public class ClientController {
    @Autowired
    private LoginService loginService;

    @Autowired
    private SecurityAdminService securityAdminService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 验证码
     */
    @GetMapping("captcha.jpg")
    @ApiOperation("验证码")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        String sessionId = request.getSession().getId();

        //获取图片验证码
        String code = ImageUtils.generationCode();

        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        operations.set(SysConstant.ADMIN_LOGIN_IMAGE_SESSION_ID + sessionId, code, 60, TimeUnit.SECONDS);

        //获取图片缓冲流
        BufferedImage image = ImageUtils.getCaptcha(code);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }

    @GetMapping("info")
    @ApiOperation("获取后台用户信息")
    public Result<AdminInfoDTO> info() {
        BaseAdmin admin = securityAdminService.getBaseAdmin();
        AdminInfoDTO dto = new AdminInfoDTO();
        BeanUtils.copyProperties(admin, dto);
        return Result.success(dto);
    }

    @PostMapping("login")
    @ApiOperation("后台登录")
    public Result login(@Valid @RequestBody LoginVO vo, HttpServletRequest request) {
        String sessionId = request.getSession().getId();
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        String code = operations.get(SysConstant.ADMIN_LOGIN_IMAGE_SESSION_ID + sessionId);
        if (code == null) {
            return Result.error("验证码已失效!请刷新再重试!");
        }
        if (!vo.getCaptcha().equals(code)) {
            return Result.error("验证码不正确!");
        }
        String token = loginService.login(vo.getAccount(), vo.getPassword());

        return Result.success(token);
    }

    @GetMapping("/logout")
    @ApiOperation("用户登出")
    public Result logout() {
        String userName = securityAdminService.getUserName();
        loginService.logout(userName);
        return Result.success();
    }
}
